<template>
  <div class="dashboard-container" style="display: grid; grid-template-columns: 4fr 1fr; grid-gap: 20px;">
    <!-- 分析表单区域 -->
    <div>
      <el-form ref="form" :model="form" label-width="80px">
        <el-form-item label="分析目标">
          <el-col :span="12"><el-input v-model="form.necessary" placeholder="请输入分析目标" /></el-col>
        </el-form-item>
        <el-form-item label="图表名称">
          <el-col :span="12"><el-input v-model="form.name" placeholder="请输入图表名称" /></el-col>
        </el-form-item>
        <el-form-item label="图表类型">
          <el-select v-model="form.chartType" :disabled="isdisabled" clearable placeholder="请先上传文件">
          <el-option
            v-for="item in options"
            :key="item.value"
            :label="item.label"
            :value="item.value">
          </el-option>
        </el-select>
        </el-form-item>
        <el-form-item label="文件上传">
          <el-upload
            action="#"
            :before-upload="beforeUpload"
            :on-preview="handlePreview"
            :on-remove="handleRemove"
            :on-success="handleSuccess"
            :on-change="handleChange"
            :file-list="fileList"
          >
            <el-button type="primary" plain>选择文件</el-button>
          </el-upload>
          <el-button type="primary" :loading="loading" @click="submitForm">提交</el-button>
          <el-button @click="reset">重置</el-button>
        </el-form-item>
      </el-form>
      
    </div>
    <!-- 图表与结论区域 -->
    <div style="display: flex; flex-direction: column;">
      <!-- 图表容器 -->
      <el-tag effect="dark" width="80px">最近图表：{{ chartName }}</el-tag>
      <div v-loading="chartLoading" style="border:1px solid #ccc">
        <div ref="chartContainer" style="width: 600px; height: 360px;"></div>
      </div>
      
      <!-- 结论区域 -->
      <el-tag effect="dark" width="80px">最近分析结果</el-tag>
      <div v-loading="chartLoading" style="border: 1px solid #ccc; padding: 1rem; overflow-y: auto; margin-top: 10px;">
        
        <p>{{ analyse }}</p>
      </div>
    </div>
  </div>
</template>

<script>
import * as echarts from 'echarts'
import { mapGetters } from 'vuex'
import { analyseData,analyseWordData,analyseDataMQ,analyseWordDataMQ } from '@/api/ai';
import { createChart,getLastChart } from '@/api/chart';
import chinaMap from '@/utils/china-main-city-map.json'//地图
import 'echarts-wordcloud';//词云

export default {
  name: 'Dashboard',
  computed: {
    ...mapGetters([
      'name'
    ])
  },
  data(){
    return{
      chartLoading:false,
      loading:false,
      chartName:"",
      form:{
        necessary:"",
        name:"",//图表名称
        chartType:"",
        file:null,
        decoration:{},//存放处理过后的构建图表的结构数据
      },
      isdisabled:true,
      options: [{
          value: '折线图',
          label: '折线图'
        }, {
          value: '柱状图',
          label: '柱状图'
        }, {
          value: '雷达图',
          label: '雷达图'
        }, {
          value: '饼图',
          label: '饼图'
        }, {
          value: '地图',
          label: '地图'
        },
        {
          value: '关系图',
          label: '关系图'
        },
        {
          value: '词云',
          label: '词云'
        }],
      fileList:[],
      analyse:"",
      showChartType:"",
    }
  },
  mounted(){
    
  },
  created(){
    this.chartLoading=true
    getLastChart({data:{userAccount:this.name}}).then(response=>{
      this.chartLoading=false
      let rawData=response.data.chartData
      let cleanedData = rawData
      this.showChartType=response.data.chartType

      cleanedData = cleanedData.replace(/\/\/.*$/gm, '');
      cleanedData = cleanedData.replace(/^\s*\n*\"|\"\n*\s*$/g, '');
      cleanedData = cleanedData.replace(/\s+/g, ' ');
      cleanedData = cleanedData.replace(/javascript/g,'');
      cleanedData = cleanedData.replace(/\`{3}/g, '');
      cleanedData = cleanedData.replace(/;.*$/, ';')

      if (!this.chartInstance) {
          this.chartInstance = echarts.init(this.$refs.chartContainer);
      }
      this.decoration=JSON.parse(cleanedData)

              //绘制出最近的图表
      echarts.registerMap('china',chinaMap)
      this.handleOptionBeforeSet();
      this.chartInstance.setOption(this.decoration);
      this.analyse=response.data.genResult
      this.chartName=response.data.name
    })
  },
  methods:{
    handleOptionBeforeSet(){//一些额外处理，比如JSON中的函数
      if(this.showChartType=="词云"){//处理下颜色
          this.decoration.series[0].textStyle.color=function() {
            var r = Math.floor(Math.random() * 256);
            var g = Math.floor(Math.random() * 256);
            var b = Math.floor(Math.random() * 256);
            return 'rgb(' + r + ',' + g + ',' + b + ')';
        };
        }
        else if(this.showChartType=="关系图"){//标签转换
          this.decoration.legend[0].data=this.decoration.series[0].categories.map(function (a) {
          return a.name;
        })
        }
    },
    reset(){

      this.form.file=null
      this.form.name=""
      this.form.necessary=""
      this.form.chartType=""
      this.fileList=[]
      this.isdisabled=true
    },
    // 提交表单
    submitForm() {
      if(this.form.file==null){
        this.$message.error('错了哦,没有上传文件呢');
      }else if(this.form.name==""){
        this.$message({
          message: '警告哦，图表名字未输入',
          type: 'warning'
        });
      }else if(this.form.chartType==""){
        this.$message({
          message: '警告哦，图表类型未选择',
          type: 'warning'
        });
      }else{
      let param=new FormData()
      param.append("file",this.form.file)
      param.append("name",this.form.name)
      param.append("necessary",this.form.necessary)
      param.append("chartType",this.form.chartType)
      param.append("userAccount",this.name)
      this.loading=true
      this.chartLoading=true
      //处理excel
      if(this.form.file.type==='application/vnd.ms-excel'||this.form.file.type==='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'){
      //同步进行分析
        //   analyseData(param).then(response=>{
      //   this.chartName=this.form.name
      //   this.analyse=response.data.analyse
      //   this.loading=false
      //   //处理数据
      //   let rawData=response.data.code
      //   let cleanedData = rawData
      //   console.log(rawData)
      //   cleanedData = cleanedData.replace(/\/\/.*$/gm, '');
      //   cleanedData = cleanedData.replace(/^\s*\n*\"|\"\n*\s*$/g, '');
      //   cleanedData = cleanedData.replace(/\s+/g, ' ');
      //   cleanedData = cleanedData.replace(/javascript/g,'');
      //   cleanedData = cleanedData.replace(/\`{3}/g, '');
      //   cleanedData = cleanedData.replace(/;.*$/, ';')
      //   console.log(cleanedData)
        
      //   if (!this.chartInstance) {
      //     this.chartInstance = echarts.init(this.$refs.chartContainer);
      //   }
      //     this.decoration=JSON.parse(cleanedData)
      //     console.log(this.decoration)
      //     echarts.registerMap('china',chinaMap)
      //     this.chartInstance.setOption(this.decoration);
      //   //加入到用户的图表数据库中
      //   this.chartLoading=false
      //   return createChart({data:{userAccount:this.name,chartName:this.form.name,goal:this.form.necessary,genResult:this.analyse,chartData:rawData,isDelete:0,chartType:this.form.chartType}})
      // }).then(response=>{
      //   console.log(response)
      // })
      //异步分析逻辑
        analyseDataMQ(param).then(response=>{
          this.$notify({
          title: '成功',
          message: '提交成功,可以在Task查看进度',
          type: 'success'
        });
        this.reset()
        })
      }//处理文本
      else if(this.form.file.type==='application/msword'||this.form.file.type==='application/vnd.openxmlformats-officedocument.wordprocessingml.document'){
        
        if(this.form.chartType!="词云"&&this.form.chartType!="关系图"){
          this.$message({
          message: '警告哦，word文档目前仅支持词云与关系图',
          type: 'warning'
        });
        }else{
          this.showChartType=this.form.chartType
          //同步分析
      //     analyseWordData(param).then(response=>{
      //   this.chartName=this.form.name
      //   this.analyse=response.data.analyse
      //   this.loading=false
      //   //处理数据
      //   let rawData=response.data.code
      //   let cleanedData = rawData
      //   console.log(rawData)
      //   cleanedData = cleanedData.replace(/\/\/.*$/gm, '');
      //   cleanedData = cleanedData.replace(/^\s*\n*\"|\"\n*\s*$/g, '');
      //   cleanedData = cleanedData.replace(/\s+/g, ' ');
      //   cleanedData = cleanedData.replace(/javascript/g,'');
      //   cleanedData = cleanedData.replace(/\`{3}/g, '');
      //   cleanedData = cleanedData.replace(/;.*$/, ';')
      //   console.log(cleanedData)
        
      //   if (!this.chartInstance) {
      //     this.chartInstance = echarts.init(this.$refs.chartContainer);
      //   }
      //     this.decoration=JSON.parse(cleanedData)
      //     this.handleOptionBeforeSet();
      //     console.log(this.decoration)
      //     this.chartInstance.setOption(this.decoration);
      //   //加入到用户的图表数据库中
      //   this.chartLoading=false
      //   return createChart({data:{userAccount:this.name,chartName:this.form.name,goal:this.form.necessary,genResult:this.analyse,chartData:rawData,isDelete:0,chartType:this.form.chartType}})
      // }).then(response=>{
      //   console.log(response)
      // })
          //异步分析
          analyseWordDataMQ(param).then(response=>{
            this.$notify({
            title: '成功',
            message: '提交成功,可以在Task查看进度',
            type: 'success'
          });
          this.reset()
          })
      }
        }
      }
      
    },
    handleChange(file,fileList){
      this.fileList=fileList
    },
    handleRemove(file, fileList) {
      this.fileList = fileList;
    },
    handlePreview(file) {
      console.log(file);
    },
    beforeUpload(file) {
      const isExcel = file.type === 'application/vnd.ms-excel' || file.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' || file.type==='application/msword' || file.type==='application/vnd.openxmlformats-officedocument.wordprocessingml.document';
      if (!isExcel) {
       this.$message.error('文件格式不支持');
        return false;
      }
      if(file.type === 'application/vnd.ms-excel'||file.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'){
      this.isdisabled=false
      this.options=[{
          value: '折线图',
          label: '折线图'
        }, {
          value: '柱状图',
          label: '柱状图'
        }, {
          value: '雷达图',
          label: '雷达图'
        }, {
          value: '饼图',
          label: '饼图'
        }, {
          value: '地图',
          label: '地图'
        }]
      }
      else if(file.type==='application/msword' || file.type==='application/vnd.openxmlformats-officedocument.wordprocessingml.document'){
        this.isdisabled=false
        this.options=[{
          value: '关系图',
          label: '关系图'
        },
        {
          value: '词云',
          label: '词云'
        }]
      }
      this.fileList.push(file)
      this.form.file = file; // 保存文件到formData

      this.$notify({
      title: '成功',
      message: '上传成功',
      type: 'success'
    });
      return false; // 阻止默认上传行为，因为我们将在提交表单时手动处理
    },
    handleSuccess(file,fileList){
      console.log(file)
    }
  }
}
</script>

<style lang="scss" scoped>
.dashboard {
  &-container {
    margin: 30px;
  }
  &-text {
    font-size: 30px;
    line-height: 46px;
  }
}
</style>
